package com.kucowka.struts.actions.chat;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.kucowka.struts.messages.Message;
import com.kucowka.struts.messages.MessageStore;
import com.opensymphony.xwork2.Action;

public class PostMessageAction implements ServletRequestAware {

	private Logger logger = LoggerFactory.getLogger(PostMessageAction.class);

	private String message;
	private List<Message> messages;

	private HttpServletRequest httpServletRequest;

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public List<Message> getMessages() {
		return messages;
	}
	
	public String execute() {

		logger.info("Got new message: " + message);
		
		HttpSession session = httpServletRequest.getSession();

		String userId = (String) session
				.getAttribute(UserRegistrationAction.USER_ID_KEY);
		String login = (String) session
				.getAttribute(UserRegistrationAction.LOGIN_ID_KEY);

		MessageStore.addMessage(login, message);

		message = null;
		messages = MessageStore.getMessages(userId);
		
		logger.info("Returning list of : " + messages.size() + " messages");

		return Action.SUCCESS;
	}

	@Override
	public void setServletRequest(HttpServletRequest httpServletRequest) {
		this.httpServletRequest = httpServletRequest;
	}
}
